package com.baizhi.controller;

import com.baizhi.entity.Category;
import com.baizhi.service.CategoryService;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("back/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @RequestMapping("show")
    public String showCategory(Model model, @RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "9")Integer pageSize){
        PageInfo<Category> pageInfo = categoryService.selectPage(pageNum, pageSize);
        model.addAttribute("pageInfo",pageInfo);
        return "forward:/back/category/show.jsp";
    }
    @RequestMapping("remove")
    public String remove(HttpSession session,Integer id,Integer pageNum,Integer pageSize){
        try {
            System.out.println("id = " + id);
            categoryService.removeCategory(id);
        }catch (Exception e){
            session.setAttribute("msg",e.getMessage());
        }
        return "redirect:/back/category/show.do?pageNum="+pageNum+"&pageSize="+pageSize+"";
    }
    @RequestMapping("add")
    public String add(HttpSession session,Category category){
        try {
            categoryService.addFirst(category);
        }catch (Exception e){
            session.setAttribute("msg",e.getMessage());
        }
        return "redirect:/back/category/show.do";
    }
    @RequestMapping("showLevel1Category")
    public String showLevel1Category(Model model){
        List<Category> categories = categoryService.selectLevel1();
        model.addAttribute("categories",categories);
        return "forward:/back/category/add-second.jsp";
    }
    @RequestMapping("showLevel2Category")
    public String showLevel2Category(Model model){
        List<Category> categories = categoryService.selectLevel2();
        System.out.println("categories = " + categories);
        model.addAttribute("categories",categories);
        return "forward:/back/book/add.jsp";
    }
}
